import 'dart:ffi';
import 'dart:convert' as convert;

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:graduation_project/cartoon_module/cartoon_view_record.dart';
import 'package:graduation_project/cartoon_module/vertical_list_view.dart';

import 'bookrack_leader_mod/bookrack_class.dart';
import 'bookrack_leader_mod/bookrack_leader_list.dart';

class Counter extends ChangeNotifier {
  //这里也可以使用with来进行实现
  bool _countstate = false;
  bool get countstate => _countstate;

  setBooState() {
    _countstate ? _countstate = false : _countstate = true;
    notifyListeners();
  }
}

class bookrack_leader extends StatefulWidget {
  bookrack_leader({Key key}) : super(key: key);

  @override
  State<bookrack_leader> createState() => _bookrack_leaderState();
}

class _bookrack_leaderState extends State<bookrack_leader> {
  bool setstate = false;
  List cartoon_list1 = [];
  int user_bookrack_class_num = 0;
  int collect_order = 0;
  List _order = ['追漫顺序', '更新时间', '最近阅读'];
  List stateList;
  Future _future;
  bool allCount = false;
  Counter _counter = new Counter();
  List user_bookrack_class = [];

  void adduser_bookrack_Class(String name) {
    // 发请求，创建一个标签表，获取表id
    this
        .user_bookrack_class
        .add({'bookrack_class_name': name, 'bookrack_list_id': 1057});
  }

  void Deluser_bookrack_Class(int e) {
    // 发请求，创建一个标签表，获取表id
    this.user_bookrack_class.removeAt(e);
    // 删除后发请求
  }

  void setuser_bookrack_Class(int e, String name) {
    this.user_bookrack_class[e]['bookrack_class_name'] = name;
  }

  @override
  void initState() {
    // TODO: implement initState
    _future = _getinformation();
    _counter.addListener(() {
      //数值改变的监听
      stateList =
          cartoon_list1.map((obj) => {...obj, "setstate": false}).toList();
    });
    super.initState();
  }

  _getinformation() async {
    print('首页调用');
    cartoon_list1 = [];
    user_bookrack_class = [];
    Response response;
    var dio = Dio();
    dio.options.responseType = ResponseType.plain;
    response = await dio.get('http://119.91.231.198:3033/getBookrackNum');
    var res = convert.jsonDecode(response.toString());
    // print(res['result'].length);
    for (var item in res['result']) {
      user_bookrack_class.add(item);
    }
    // print(user_bookrack_class);
    //
    Response response0;
    response0 = await dio.get(
        'http://119.91.231.198:3033/getBookrackValue?bookrack_id=' +
            user_bookrack_class[user_bookrack_class_num]['bookrack_id']
                .toString());
    var res0 = convert.jsonDecode(response0.toString());

    for (var item in res0['valueList']) {
      cartoon_list1.add(item);
    }
    cartoon_list1
        .sort((a, b) => (b['collect_date']).compareTo(a['collect_date']));
    cartoon_list1.map((e) => {});
    stateList =
        cartoon_list1.map((obj) => {...obj, "setstate": false}).toList();
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
        initialIndex: 0,
        length: 3,
        child: Scaffold(
          appBar: PreferredSize(
            preferredSize: Size.fromHeight(60),
            child: AppBar(
              backgroundColor: Color.fromRGBO(255, 250, 250, 1),
              title: Row(
                children: <Widget>[
                  Expanded(
                    flex: 1,
                    child: Container(),
                  ),
                  Expanded(
                    flex: 3,
                    child: TabBar(
                        indicatorColor: Colors.black87,
                        indicatorSize: TabBarIndicatorSize.label,
                        // indicatorWeight: 0,
                        labelColor: Colors.black87,
                        unselectedLabelColor: Colors.black54,
                        labelStyle: TextStyle(fontSize: 16),
                        unselectedLabelStyle: TextStyle(fontSize: 14),
                        // controller: _controller,
                        tabs: <Tab>[
                          Tab(text: "追漫"),
                          Tab(text: "历史"),
                          Tab(text: "缓存"),
                          // Tab(text: "热番原作"),
                        ]),
                  ),
                  Expanded(
                    flex: 1,
                    child: Container(
                      width: 100,
                      // color: Colors.red,
                      margin: EdgeInsets.only(
                        left: 35,
                      ),
                      child: InkWell(
                        onTap: () {
                          print('编辑');
                          // _counter.addCount();
                          setState(() {
                            // setstate ? setstate = false : setstate = true;
                            _counter.setBooState();
                          });
                        },
                        child: Text(
                          '编辑',
                          style: TextStyle(color: Colors.black87, fontSize: 14),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          body: FutureBuilder(
            future: _future,
            builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                return TabBarView(
                  children: <Widget>[
                    Container(
                      child: Stack(
                        children: [
                          Positioned(
                            top: 0,
                            height: 40,
                            width: MediaQuery.of(context).size.width,
                            child: Row(
                              children: _order.asMap().keys.map((e) {
                                return Expanded(
                                    flex: 1,
                                    child: InkWell(
                                      onTap: () {
                                        // print(e);
                                        setState(() {
                                          collect_order = e;
                                          switch (e) {
                                            case 0:
                                              setState(() {
                                                stateList.sort((a, b) =>
                                                    (b['collect_date'])
                                                        .compareTo(
                                                            a['collect_date']));
                                              });
                                              break;
                                            case 1:
                                              setState(() {
                                                stateList.sort((a, b) =>
                                                    (b['new_date']).compareTo(
                                                        a['new_date']));
                                              });
                                              break;
                                            case 2:
                                              setState(() {
                                                stateList.sort((a, b) =>
                                                    (b['read_date']).compareTo(
                                                        a['read_date']));
                                              });
                                              break;

                                            default:
                                          }
                                        });
                                      },
                                      child: Container(
                                        margin: EdgeInsets.only(
                                            left: 10, right: 10, top: 10),
                                        decoration: new BoxDecoration(
                                          // border: new Border.all(color: Color(0xFFFF0000), width: 0.5), // 边色与边宽度
                                          color: collect_order == e
                                              ? Color.fromRGBO(226, 243, 253, 1)
                                              : Color.fromRGBO(
                                                  241, 241, 243, 1), // 底色
                                          //        borderRadius: new BorderRadius.circular((20.0)), // 圆角度
                                          borderRadius: new BorderRadius.all(
                                              Radius.circular(
                                                  50)), // 也可控件一边圆角大小
                                        ),
                                        alignment: Alignment.center,
                                        child: Text(
                                          _order[e],
                                          style: TextStyle(
                                              color: collect_order == e
                                                  ? Color.fromRGBO(
                                                      51, 169, 255, 1)
                                                  : Color.fromRGBO(
                                                      109, 111, 126, 1)),
                                        ),
                                      ),
                                    ));
                              }).toList(),
                            ),
                          ),
                          bookrack_leader_list(
                            cartoon_list1: stateList,
                            setstate: _counter.countstate,
                            allCounter: (value) {
                              print(value);
                              setState(() {
                                allCount = value;
                              });
                            },
                          ),
                          Positioned(
                            bottom: 40,
                            height: 45,
                            child: InkWell(
                              onTap: () {
                                showModalBottomSheet<Void>(
                                    context: context,
                                    builder: (BuildContext context) {
                                      return bookrack_class(
                                        user_bookrack_class:
                                            user_bookrack_class,
                                        user_bookrack_class_num:
                                            user_bookrack_class_num,
                                        NumChange: (value) {
                                          setState(() {
                                            _future = _getinformation();
                                            user_bookrack_class_num = value;
                                          });
                                        },
                                        setList: _getinformation,
                                        // set: this.setuser_bookrack_Class(),
                                      );
                                    });
                              },
                              child: Container(
                                decoration: new BoxDecoration(
                                  color: Color.fromRGBO(255, 255, 255, 1),
                                  border: new Border.all(
                                      color: Colors.black38,
                                      width: 0.5), // 边色与边宽度
                                ),
                                width: MediaQuery.of(context).size.width,
                                // color: Colors.red,
                                child: Row(children: [
                                  Container(
                                    margin: EdgeInsets.only(left: 8, bottom: 6),
                                    child: Text(
                                      user_bookrack_class[
                                                  user_bookrack_class_num]
                                              ['bookrack_name'] +
                                          '(' +
                                          user_bookrack_class[
                                                      user_bookrack_class_num]
                                                  ['bookrack_list']
                                              .toString() +
                                          ')',
                                      style: TextStyle(color: Colors.black54),
                                    ),
                                  ),
                                  Expanded(child: SizedBox()),
                                  Container(
                                      margin:
                                          EdgeInsets.only(right: 8, bottom: 6),
                                      child: Icon(Icons.keyboard_arrow_up,
                                          color: Colors.black54))
                                ]),
                              ),
                            ),
                          ),
                          Positioned(
                            bottom: 40,
                            height: 60,
                            child: Offstage(
                              offstage: !_counter.countstate,
                              child: Container(
                                decoration: new BoxDecoration(
                                  color: Color.fromRGBO(255, 255, 255, 1),
                                  border: new Border.all(
                                      color: Colors.black38,
                                      width: 0.5), // 边色与边宽度
                                ),
                                width: MediaQuery.of(context).size.width,
                                child: Row(
                                  children: [
                                    Expanded(
                                        flex: 1,
                                        child: InkWell(
                                          onTap: () {
                                            setState(() {
                                              allCount
                                                  // ignore: unnecessary_statements
                                                  ? {
                                                      allCount = false,
                                                      stateList = cartoon_list1
                                                          .map((obj) => {
                                                                ...obj,
                                                                "setstate":
                                                                    false
                                                              })
                                                          .toList()
                                                    }
                                                  // ignore: unnecessary_statements
                                                  : {
                                                      allCount = true,
                                                      stateList = cartoon_list1
                                                          .map((obj) => {
                                                                ...obj,
                                                                "setstate": true
                                                              })
                                                          .toList()
                                                    };
                                            });
                                          },
                                          child: Container(
                                              margin:
                                                  EdgeInsets.only(bottom: 10),
                                              alignment: Alignment.center,
                                              child: Text(
                                                allCount ? '全不选' : '全选',
                                                style: TextStyle(fontSize: 16),
                                              )),
                                        )),
                                    Expanded(
                                        flex: 1,
                                        child: Container(
                                            margin: EdgeInsets.only(bottom: 10),
                                            alignment: Alignment.center,
                                            child: Text(
                                              '收藏至',
                                              style: TextStyle(fontSize: 16),
                                            ))),
                                    Expanded(
                                        flex: 1,
                                        child: Container(
                                            margin: EdgeInsets.only(bottom: 10),
                                            alignment: Alignment.center,
                                            child: Text(
                                              '删除',
                                              style: TextStyle(fontSize: 16),
                                            ))),
                                  ],
                                ),
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                    cartoon_view_record(),
                    Container()
                  ],
                );
              } else {
                return Container();
              }
            },
          ),
        ));
  }
}
